package com.hk.core.web;

import com.hk.commons.util.Constants;
import com.hk.commons.util.StringUtils;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Objects;

/**
 * 可重复读取 body的 请求封装
 *
 * @author Kevin
 */
public class RepeatReadHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private String buffer;

    public RepeatReadHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public String getCharacterEncoding() {
        return StringUtils.defaultIfEmpty(super.getCharacterEncoding(), Constants.UTF_8);
    }

    /**
     * body 支持重复读取
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (Objects.isNull(this.buffer)) {
            var inputStream = super.getInputStream();
            this.buffer = StringUtils.defaultIfEmpty(
                    enhanceBody(StreamUtils.copyToString(inputStream, Charset.forName(getCharacterEncoding()))), StringUtils.EMPTY);
        }
        return new PostServletInputStream(this.buffer);
    }

    /**
     * 对body的内容处理
     */
    protected String enhanceBody(String body) {
        return body;
    }

}
